<?php


namespace app\api\service;

use app\admin\service\AdminPhoto;
use app\api\model\UserList;
use app\common\validate\CommonValidate;
use think\exception\ValidateException;
use think\facade\Request;

class SystemService
{
    public static function sendEmail(): array
    {
        $data = Request::post();
        $rule = [
            'address' => 'require',
            'title' => 'require',
            'content' => 'require',
        ];
        $message = [
            'address.require' => "收件人不能为空",
            'title.require' => "邮件标题不能为空",
            'content.require' => "邮件内容不能为空",
        ];
        $check = Request::checkToken('__token__', $data);
        if (false === $check) {
            throw new ValidateException('invalid token');
        }
        if (($msg = CommonValidate::check($rule, $message, $data)) !== true)
            return ['msg' => $msg, 'code' => 201];
        foreach ($data as $key => $value) {
            if (strstr($key, 'file') !== false && strstr($key, 'name_file') == false) {
                $indexArr = explode('[', $key);
                $index = $indexArr[1] ?? '';
                $index = explode(']', $index)[0];

                $data['file'][] = [
                    'file' => root_path() . 'public' . dealImage($value, 0),
                    'file_name' => $data["name_file[$index]"],
                ];
                unset($data[$key]);
                unset($data["name_file[$index]"]);
            }
        }
        $ret = Mail::go($data['address'], $data['title'], $data['content'], $data['file'] ?? []);
        return ['code' => (int)$ret['code'], 'msg' => $ret['msg']];
    }

    //通用上传
    public static function putFile($file, $type, $path)
    {
        global $globalConfig;
        $fileType = $globalConfig['file_type'] ?? 1;
        if (!$path) $path = 'default';
        try {
            if ($type == 'image') {
                $fileSize = $globalConfig['imgValidate_size'] ? $globalConfig['imgValidate_size'] * 1024 : config('procedure.uploadValidate.imgValidate.validate.size');
                $fileExt = implode(',', explode('|', $globalConfig['imgValidate_ext'] ?: config('procedure.uploadValidate.imgValidate.validate.ext')));
            } elseif ($type == 'video') {
                $fileSize = $globalConfig['videoValidate_size'] ? $globalConfig['videoValidate_size'] * 1024 : config('procedure.uploadValidate.videoValidate.validate.size');
                $fileExt = implode(',', explode('|', $globalConfig['videoValidate_ext'] ?: config('procedure.uploadValidate.videoValidate.validate.ext')));
            } elseif ($type == 'audio') {
                $fileSize = $globalConfig['audioValidate_size'] ? $globalConfig['audioValidate_size'] * 1024 : config('procedure.uploadValidate.audioValidate.validate.size');
                $fileExt = implode(',', explode('|', $globalConfig['audioValidate_ext'] ?: config('procedure.uploadValidate.audioValidate.validate.ext')));
            } else {
                $fileSize = $globalConfig['fileValidate_size'] ? $globalConfig['fileValidate_size'] * 1024 : config('procedure.uploadValidate.fileValidate.validate.size');
                $fileExt = implode(',', explode('|', $globalConfig['fileValidate_ext'] ?: config('procedure.uploadValidate.fileValidate.validate.ext')));
            }
            validate(['file' => [
                'fileSize' => $fileSize,
                'fileExt' => $fileExt,
            ]])->check(['file' => $file]);
        } catch (\think\exception\ValidateException $e) {
            return [201, $e->getMessage(), []];
        }
        if ($fileType == 2) {
            //阿里云上传
            $res = Oss::alYunOSS($file, $file->extension(), $path);
            if ($res["code"] == 201) {
                return [201, $res["msg"], []];
            }
            $url = $res['src'];
            AdminPhoto::add($file, $url, $path, 2);
        } elseif ($fileType == 3) {
            //七牛上传
            $res = Qiniu::QiniuOSS($file, $file->extension(), $path);
            if ($res["code"] == 201) {
                return [201, $res["msg"], []];
            }
            $url = $res['src'];
            AdminPhoto::add($file, $url, $path, 3);
        } else {
            $savename = '/' . 'upload' . '/' . \think\facade\Filesystem::disk('public')->putFile($path, $file);
            $url = str_replace("\\", "/", $savename);
            AdminPhoto::add($file, $url, $path, 1);
        }

        return [200, '上传成功', ['url' => dealImage($url)]];
    }

    public static function sendVerificationCode($params)
    {
        $account = $params['account'];
        $code = rand(100000, 999999);
        switch ($params['scene']) {
            case 'register':
                $exist = UserList::getInfoByAccount($account);
                if ($exist) return [201, '账号已存在', []];
                $title = '注册验证码';
                $content = '<p style="text-align: left;"><span style="color: #000000;">您的注册验证码是：<span style="color: #3598db;"><span style="font-size: 14pt;">' . $code . '</span>&nbsp;<span style="color: #000000;">验证码5分钟内有效！</span></span></span></p>';
                break;
            case 'forget':
                $exist = UserList::getInfoByAccount($account);
                if (!$exist) return [201, '账号不存在', []];
                $title = '忘记密码验证码';
                $content = '<p style="text-align: left;"><span style="color: #000000;">您的验证码是：<span style="color: #3598db;"><span style="font-size: 14pt;">' . $code . '</span>&nbsp;<span style="color: #000000;">验证码5分钟内有效！</span></span></span></p>';
                break;
            case 'login':
                $exist = UserList::getInfoByAccount($account);
                if (!$exist) return [201, '账号不存在', []];
                $title = '登录验证码';
                $content = '<p style="text-align: left;"><span style="color: #000000;">您的验证码是：<span style="color: #3598db;"><span style="font-size: 14pt;">' . $code . '</span>&nbsp;<span style="color: #000000;">验证码5分钟内有效！</span></span></span></p>';
                break;
            default:
                return [201, '参数错误', []];
        }
        UserCode::writeUserCode($account, $params['scene'], $code);
        if ($params['back'] ?? 0) return [200, '操作成功', ['code' => $code]];
        $ret = Mail::go($account, $title, $content);
        return [(int)$ret['code'], $ret['msg'], []];
    }

    public static function getWithdrawalConfig($globalConfig)
    {
        $data = [];
        $data['min_money'] = $globalConfig['withdraw_min_money'] ?? 0;
        $data['max_money'] = $globalConfig['withdraw_max_money'] ?? 1000;
        $data['content'] = $globalConfig['withdraw_remark'] ?? '';
        return [200, '上传成功', $data];
    }
}